package com.woniuxy.permission.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.zsd.commons.core.exception.ZsdException;
import com.woniuxy.permission.entity.Permission;
import com.woniuxy.permission.entity.Role;
import com.woniuxy.permission.entity.RoleResource;
import com.woniuxy.permission.form.AddRoleForm;
import com.woniuxy.permission.mapper.PermissionMapper;
import com.woniuxy.permission.mapper.RoleMapper;
import com.woniuxy.permission.mapper.RoleResourceMapper;
import com.woniuxy.permission.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-13
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RoleResourceMapper roleResourceMapper; // 关联表Mapper


    @Override
    public void addRole(AddRoleForm form) throws Exception {
        // 检查角色编码是否符合要求（只能是英文，不能带符号）
        if (!form.getRoleCode().matches("^[a-zA-Z]+$")) {
            throw new ZsdException("角色编码只能是英文，不能带符号", 500);
        }

        // 检查角色名是否已存在
        QueryWrapper<Role> roleNameQueryWrapper = new QueryWrapper<>();
        roleNameQueryWrapper.eq("role_name", form.getRoleName());
        Role existingRoleByName = roleMapper.selectOne(roleNameQueryWrapper);
        if (existingRoleByName != null) {
            throw new ZsdException("角色名已存在，无法添加新角色", 500);
        }

        // 检查角色编码是否已存在
        QueryWrapper<Role> roleCodeQueryWrapper = new QueryWrapper<>();
        roleCodeQueryWrapper.eq("role_code", form.getRoleCode());
        Role existingRoleByCode = roleMapper.selectOne(roleCodeQueryWrapper);
        if (existingRoleByCode != null) {
            throw new ZsdException("角色编码已存在，无法添加新角色", 500);
        }

        // 如果角色名和角色编码都不存在，则插入新角色
        Role newRole = new Role();
        newRole.setRoleName(form.getRoleName());
        newRole.setRoleCode(form.getRoleCode());

        roleMapper.insert(newRole);
    }

    @Override
    public void deleteRole(Integer roleId) throws Exception {
        // 创建查询条件，检查角色下是否有用户
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);

        // 查询数据库中是否存在该角色下的用户
        Long count = permissionMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new ZsdException("该角色下有用户，无法删除", 500);
        }

        // 如果没有用户，则删除角色
        int deleteCount = roleMapper.deleteById(roleId);
        if (deleteCount <= 0) {
            throw new ZsdException("删除角色失败", 500);
        }
    }

    @Override
    public Object getAllRole() throws Exception {
        return roleMapper.selectList(null);
    }

    @Override
    public void assignResources(Integer roleId, List<Integer> resourceIds) {
        // 1. 删除该角色原有的所有资源关联（避免脏数据）
        QueryWrapper<RoleResource> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.eq("role_id", roleId);
        roleResourceMapper.delete(deleteWrapper);

        // 2. 插入新的资源关联（如果有选中的资源）
        if (!CollectionUtils.isEmpty(resourceIds)) {
            List<RoleResource> newRoleResources = new ArrayList<>();
            for (Integer resourceId : resourceIds) {
                RoleResource roleResource = new RoleResource();
                roleResource.setRoleId(roleId);
                roleResource.setResourceId(resourceId);
                newRoleResources.add(roleResource);
            }
            for (RoleResource roleResource : newRoleResources) {
                roleResourceMapper.insert(roleResource);
            }
        }
    }

}
